package com.example.user.service;


import com.example.user.common.Result;
import com.example.user.entity.User;
import com.example.user.entity.UserLogin;
import com.example.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {


    @Autowired
    private UserMapper userMapper;

    public List<User> getUserPage() {

        List<User> userPage = userMapper.getUserPage();
        return userPage;
    }

    public Result deleteUserById(Integer id) {
        int count = userMapper.deleteById(id);
        if (count == 0) {
            return Result.error("400", "删除失败");
        }
        return Result.success("删除成功");

    }

    public Result addUser(User user) {
        int count = userMapper.addUser(user);
        if (count == 0) {
            return Result.error("400", "添加失败");
        }
        return Result.success("添加成功");
    }

    public List<User> getUserByName(String userName) {

        List<User> users = userMapper.getUserByName(userName);
        return users;

    }

    public Result editUserInfo(User user) {

        int count = userMapper.editUserInfo(user);
        if (count == 0) {
            return Result.error("400", "编辑失败");
        }
        return Result.success("编辑成功");


    }

    public Result login(UserLogin user) {

        UserLogin userLogin = userMapper.getUserLoingInfo(user);
        String username = userLogin.getUsername();
        String password = userLogin.getPassword();
        if (username == null && password == null) {
            return Result.error("400", "登录失败");
        }
        return Result.success("登录成功");


    }

    public Result register(UserLogin user) {
        UserLogin userRegister = userMapper.getUserLoingInfo(user);

        if (userRegister != null) {
            String username = userRegister.getUsername();
            String password = userRegister.getPassword();
            if (username != null && password != null) {
                return Result.error("400", "用户已经存在");
            }
        }


        int count = userMapper.insertUserRegister(user);
        if (count == 0) {
            return Result.error("400", "注册失败");
        }
        return Result.success("注册成功");


    }

    public Result selectUserById(Integer id) {

      User user=  userMapper.selectUserById(id);
      if (user != null) {
          return Result.error("400","该用户不存在");
      }
      return Result.success(user);
    }
}
